import { startRoutes,adminRoutes,studentRoutes } from '@/router'
// import fa from "element-ui/src/locale/lang/fa";

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
    const res = []
    console.log('routes + roles')
    console.log(routes)
    console.log(roles)
    routes.forEach(route => {
        const tmp = { ...route }
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })

    return res
}

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = startRoutes.concat(routes)
    },
    IS_EMPTY: (routes) => {
        if (routes.name == null) {
            console.log("执行了true")
            return true
        }
        console.log("执行了false")
        return false
    }
}

const actions = {
    generateRoutes({ commit }, roles) {
        return new Promise(resolve => {
            let accessedRoutes
            // if (roles.includes('admin')) {
            //   accessedRoutes = asyncRoutes || []
            // } else {
            //   accessedRoutes = filterAsyncRoutes(adminLogin, roles)
            // }
            const type = localStorage.getItem("type");
            // alert("aaaa"+type);
            // 这里的type指的是用户登录的角色，比如1是管理员，2是学生
            if(type == "1"){
                accessedRoutes = filterAsyncRoutes(adminRoutes, roles)
            }else if (type == "2"){
                accessedRoutes = filterAsyncRoutes(studentRoutes, roles)
            }
            // console.log(accessedRoutes);
            // console.log('accessedRoutes');
            commit('SET_ROUTES', accessedRoutes)
            resolve(accessedRoutes)
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
